package com.learn.threadLocal;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author ln
 * @Description: ${todo}
 * @date 2020/12/26
 */
public class JdbcUtil {
    static ThreadLocal<Connection> t=new ThreadLocal<>();

//    连接池对象
    private static final DataSource dataSource=new DruidDataSource();

    /**
     * 原本：直接从连接池中获取
     * 现在：
     *      1.直接获取当前线程绑定的连接对象
     *      2.如果连接对象是空的
     *          1.再去连接池获取连接
     *          2.将此连接对象跟当前线程进行绑定
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        Connection con = t.get();
        if(con==null){
            con=dataSource.getConnection();
            t.set(con);
        }
        return con;
//        return dataSource.getConnection();
    }
}
